/*
 * tools.c
 *
 *  Created on: 2014年12月22日
 *      Author: chens
 */

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>

/* 根据ip地址和端口创建一个IP4的TCP监听套接字 */
int inet4_tcp_server(const char *ip, unsigned short port)
{
	int fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd == -1) {
		perror("socket");
		return -1;
	}

	struct sockaddr_in addr;
	socklen_t len = sizeof(addr);
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	if (ip == NULL) {
		addr.sin_addr.s_addr = INADDR_ANY;
	} else {
		if (!inet_aton(ip, &(addr.sin_addr))) {
			close(fd);
			return -1;
		}
	}

	int opt = 1;
	setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

	if (-1 == bind(fd, (struct sockaddr*) &addr, len)) {
		perror("bind");
		close(fd);
		return -1;
	}

	if (-1 == listen(fd, 5)) {
		perror("listen");
		close(fd);
		return -1;
	}

	return fd;
}

int inet4_tcp_client(const char *ip, unsigned short port)
{
	int fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd == -1) {
		perror("socket");
		return -1;
	}

	struct sockaddr_in addr;
	socklen_t len = sizeof(addr);
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	inet_aton(ip, &(addr.sin_addr));

	if (0 != connect(fd, (struct sockaddr*) &addr, len)) {
		close(fd);
		perror("connect");
		return -1;
	}
	return fd;
}

